package me.qingy.programmatic;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * 从后向前扫描
 *
 * @author qingy
 * @since 2021/8/19
 */
public class LengthOfLastWord {

    public int lengthOfLastWord(String s) {
        char[] chars = s.toCharArray();
        int k = 0;
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] == ' ' && k != 0) {
                return k;
            } else if (!(chars[i] == ' ')) {
                k++;
            }
        }
        return k;
    }

    public int lengthOfLastWordWithoutToChar(String s) {
        int k = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == ' ' && k != 0) {
                return k;
            } else if (!(s.charAt(i) == ' ')) {
                k++;
            }
        }
        return k;
    }

    @Test
    public void testLengthOfLastWord() {
        Assertions.assertEquals(5, lengthOfLastWord("Hello World"));
        Assertions.assertEquals(4, lengthOfLastWord("   fly me   to   the moon  "));
        Assertions.assertEquals(6, lengthOfLastWord("luffy is still joyboy"));
        Assertions.assertEquals(1, lengthOfLastWord("a"));
    }
}
